package com.example.dessertstoressm.controller;

import com.example.dessertstoressm.Service.AccountService;
import com.example.dessertstoressm.Service.CatalogService;
import com.example.dessertstoressm.Service.SendSmsService;
import com.example.dessertstoressm.domain.Account;
import com.example.dessertstoressm.domain.Product;
import com.example.dessertstoressm.domain.SignOn;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

@Controller
//@SessionAttributes(value={"username","password","tryUsername","tryPassword","account","listed","usernameSignOut"})
public class accountController {

    public String msg;
    @Resource
    public AccountService accountService;
    @Resource
    public CatalogService catalogService;

    private String msg_username;
    private String msg_password;
    private String msg_repeated_password;
    private String msg_firstname;
    private String msg_lastname;
    private String msg_email;
    private String msg_phone;
    private String msg_address1;
    private String msg_address2;
    private String msg_city;
    private String msg_state;
    private String msg_zip;
    private String msg_country;


    @Autowired
    public Account account;

    @PostMapping("register")
    public String register(@RequestParam("username") String username,
                           @RequestParam("account.firstName") String firstName,
                           @RequestParam("account.lastName") String lastName,
                           @RequestParam("account.email") String email,
                           @RequestParam("phone") String phone,
                           @RequestParam("account.address1") String address1,
                           @RequestParam("account.address2") String address2,
                           @RequestParam("account.city") String city,
                           @RequestParam("account.state") String state,
                           @RequestParam("account.zip") String zip,
                           @RequestParam("account.country") String country,
                           @RequestParam("account.languagePreference") String languagePreference,
                           @RequestParam("account.favouriteCategoryId") String favouriteCategoryId,
                           @RequestParam("account.listOption") String listOption,
                           @RequestParam("account.bannerOption") String bannerOption,
                           @RequestParam("password") String password,
                           @RequestParam("repeatedPassword") String repeatedPassword,
                           Model model, HttpServletRequest req
    ) {

        HttpSession session = req.getSession();
        account.setUsername(username);
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setEmail(email);
        account.setPhone(phone);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setCountry(country);
        account.getProfile().setLanguagePreference(languagePreference);
        account.getProfile().setFavouriteCategoryId(favouriteCategoryId);
        account.getProfile().setListOption(listOption != null);
        account.getProfile().setBannerOption(bannerOption != null);

        String pwd = password;
        String repeatPwd = repeatedPassword;

        account.getSignOn().setPassword(password);


        //用户名
        Account newAccount = accountService.getAccountByUsername(account.getUsername());
        if (newAccount != null) {
            this.msg_username = "用户名已存在";
            req.setAttribute("msg_username", this.msg_username);

            return "account/newAccount";
        } else {

            //注册成功
            accountService.insertAccount(account);

            account.getSignOn().setPassword(null);
            session.setAttribute("account", account);

            if (account.getProfile().isListOption()) {
                List<Product> myList = catalogService.getProductListByCategory(account.getProfile().getFavouriteCategoryId());
                session.setAttribute("myList", myList);
                session.setAttribute("listed", "1");
            }


            return "catalog/main";

        }
    }


//    private boolean validate(){
//        if(usernameIsRight() & passwordIsRight() & firstnameIsRight() & lastnameIsRight() & emailIsRight() &
//                phoneIsRight() & address1IsRight() & address2IsRight() & cityIsRight() & stateIsRight() &
//                zipIsRight() & countryIsRight()){
//            return true;
//        } else {
//            return false;
//        }
//    }
//
//    private boolean usernameIsRight(){
//        if(account.getUsername() == null || account.getUsername().equals("")){
//            this.msg_username = "用户名不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean passwordIsRight(){
//        if(account.getSignOn().getPassword() == null || account.getSignOn().getPassword().equals("")){
//            this.msg_password = "密码不能为空";
//            return false;
//        }
//        if(account.getSignOn().getPassword().length()<6||account.getSignOn().getPassword().length()>19){
//            this.msg_password = "密码长度需为6~20位";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean firstnameIsRight(){
//        if(account.getFirstName() == null || account.getFirstName().equals("")){
//            this.msg_firstname = "名不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean lastnameIsRight(){
//        if(account.getLastName() == null || account.getLastName().equals("")){
//            this.msg_lastname = "姓不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean emailIsRight(){
//        if(account.getEmail() == null || account.getEmail().equals("")){
//            this.msg_email = "邮箱不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean phoneIsRight(){
//        if(account.getPhone() == null || account.getPhone().equals("")){
//            this.msg_phone = "电话不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean address1IsRight(){
//        if(account.getAddress1() == null || account.getAddress1().equals("")){
//            this.msg_address1 = "地址1不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean address2IsRight(){
//        if(account.getAddress2() == null || account.getAddress2().equals("")){
//            this.msg_address2 = "地址2不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean cityIsRight(){
//        if(account.getCity() == null || account.getCity().equals("")){
//            this.msg_city = "城市不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean stateIsRight(){
//        if(account.getState() == null || account.getState().equals("")){
//            this.msg_state = "州不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean zipIsRight(){
//        if(account.getZip() == null || account.getZip().equals("")){
//            this.msg_zip = "邮编不能为空";
//            return false;
//        }
//        return true;
//    }
//
//    private boolean countryIsRight(){
//        if(account.getCountry() == null || account.getCountry().equals("")){
//            this.msg_country = "国家不能为空";
//            return false;
//        }
//        return true;
//    }

    //以下为加入手机验证码登录——————————————————————————————————————————————
    @Resource
    SendSmsService sendSmsService;

    private String code;
    private String phone;

    @PostMapping("/send")
    public String sendSms(HttpServletRequest req) {
        System.out.println("__________");
        System.out.println(req.getParameter("phone"));

        HttpSession session = req.getSession();
        this.phone = req.getParameter("phone");
        session.setAttribute("tryPhone", phone);
        session.setAttribute("loginMethod", 2);

        Account account = accountService.getAccountByPhone(phone);
        if (account == null) {
            session.setAttribute("signOnMsg", "该手机号无账号");
        } else {
            this.code = sendSmsService.getCode();
            System.out.println(this.code);
            //发送验证码
            try {
                sendSmsService.sendMessage(phone, code);
                session.setAttribute("signOnMsg", "验证码已发送");
            } catch (Exception e) {
                e.printStackTrace();
                session.setAttribute("signOnMsg", "验证码发送失败，请稍后再试");
            }
        }
        return "account/signon";
    }

    @PostMapping("signOn")
    public String signOnCheck(Model model, HttpServletRequest req) {
        System.out.println("++++++++++++++");

        String loginMethod = req.getParameter("loginMethod");
        System.out.println(loginMethod + "____________");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phoneCheck = req.getParameter("phone");
        String codeCheck = req.getParameter("code");
        HttpSession session = req.getSession();
        session.setAttribute("tryUsername", username);
        session.setAttribute("tryPassword", password);
        session.setAttribute("tryPhone", phoneCheck);
        session.setAttribute("loginMethod", loginMethod);

        ModelAndView modelAndView = new ModelAndView();
        System.out.println(username + password);
        if (!loginMethod.equals("2")) {
            //检验用户或密码
            Account account = accountService.getAccountByUsername(username);
            if (account == null) {
                this.msg = "该账号不存在";
                return "account/signon";
            } else {
                String rightPassword = account.getSignOn().getPassword();
                System.out.println(account + rightPassword);
                if (!Objects.equals(DigestUtils.md5DigestAsHex(password.getBytes()), rightPassword)) {
                    this.msg = "用户名或密码错误";
                    session.setAttribute("signOnMsg", this.msg);

                    return "account/signon";
                } else {
                    session.setAttribute("signOnMsg", "");
                    session.setAttribute("tryPassword", null);
                    session.setAttribute("account", account);

                    return "catalog/main";
                }
            }
        } else {
            //检验手机号码和验证码
            System.out.println(this.phone);
            if (!Objects.equals(this.phone, phoneCheck)) {
                this.msg = "该手机号未接收过验证码";
                session.setAttribute("signOnMsg", this.msg);

                return "account/signon";
            } else {
                Account account = accountService.getAccountByPhone(phoneCheck);
                if (account == null || !Objects.equals(codeCheck, code)) {
                    this.msg = "手机号或验证码不正确";
                    session.setAttribute("signOnMsg", this.msg);

                    return "account/signon";
                } else {
                    session.setAttribute("signOnMsg", "");
                    session.setAttribute("account", account);

                    return "catalog/main";
                }
            }
        }

    }

    //以下为注册————————————————————————————————-
    //检验账号重复
    @GetMapping("IsUsernameExist")
    public void usernameCheck(HttpServletRequest req) {
        HttpSession session = req.getSession();
        //调用service dao查询username是否可用
        String username = req.getParameter("username");
        Account newAccount = accountService.getAccountByUsername(username);

        if (newAccount != null) {
            session.setAttribute("msg_username", "用户名已存在");
        } else {
            session.setAttribute("msg_username", "");
        }
    }

    @PostMapping("/sendCode1")
    public void sendCode1(HttpServletRequest req) {
        System.out.println("----------------");
        System.out.println(req.getParameter("phone"));

        HttpSession session = req.getSession();

        Account account = accountService.getAccountByPhone(phone);
        if (account != null) {
            session.setAttribute("msg_phone", "该手机号已有账号，请前往登录");
        } else {
            this.code = sendSmsService.getCode();
            System.out.println(this.code);
            //发送验证码
            try {
                sendSmsService.sendMessage(phone, code);
                session.setAttribute("msg_phone", "验证码已发送");
            } catch (Exception e) {
                e.printStackTrace();
                session.setAttribute("msg_phone", "验证码发送失败，请稍后再试");
            }
        }
    }

    @PostMapping("/checkCode")
    public void checkCode1(HttpServletRequest req){
        HttpSession session = req.getSession();

        String phoneCheck = req.getParameter("phone");
        String codeCheck = req.getParameter("code");

        //检验手机号码和验证码
        System.out.println(this.phone);
        System.out.println(this.code);
        if (!Objects.equals(this.phone, phoneCheck)) {
            session.setAttribute("msg_code", "该手机号未接收过验证码");
        } else {
            if (!Objects.equals(codeCheck, code)) {
                session.setAttribute("msg_code", "验证码不正确");
            } else {
                session.setAttribute("msg_code", "");
            }
        }
    }

    @PostMapping("/sendCode2")
    public void sendCode2(HttpServletRequest req) {
        System.out.println("-------------------");
        System.out.println(req.getParameter("phone"));

        HttpSession session = req.getSession();

        Account account = accountService.getAccountByPhone(phone);

        if (account != null) {
            String username = req.getParameter("username");
            String usernameOfPhone = account.getUsername();

            if (Objects.equals(username, usernameOfPhone)) {
                session.setAttribute("msg_phone", "手机号未更改");
            } else {
                session.setAttribute("msg_phone", "该手机号已有账户");
            }

        } else {
            this.code = sendSmsService.getCode();
            System.out.println(this.code);
            //发送验证码
            try {
                sendSmsService.sendMessage(phone, code);
                session.setAttribute("msg_phone", "验证码已发送");
            } catch (Exception e) {
                e.printStackTrace();
                session.setAttribute("msg_phone", "验证码发送失败，请稍后再试");
            }
        }
    }

}



